<template>
  <div v-if="flag">
    <el-select
      v-select-scroll
      v-if="!element.options.useDialog"
      v-model="computedValue"
      :multiple="element.options.multiple"
      :placeholder="element.options.placeholder || '请选择'"
      :disabled="element.options.disabled && !isInDetail"
      :filter-method="filterData"
      value-key="id"
      filterable
      clearable
      size="small"
      class="width240"
      @clear="handleClear"
      @change="handleChange"
    >
      <Options v-for="item in defaultValue" :item="item" :key="'hide'+item.id" show-check-user class="hide" />
      <Options v-for="user in userList" :item="user" :key="user.id" show-check-user />
    </el-select>
    <div v-else :class="{'disabled':element.options.disabled && !isInDetail}" class="user-select-input input width240" @click="addSender">
      <template v-if="computedValue && ((!element.options.multiple && computedValue.id) || (element.options.multiple && computedValue.length))" >
        <div class="value ellipsisOne">{{ modelValue }}</div>
        <i class="el-icon-circle-close icon" @click.stop="clearUser"/>
      </template>
      <div v-else class="placeholder ellipsisOne">{{ element.options.placeholder || '请选择' }}</div>
      <DiversAuditorDialog ref="auditorDialog" @userSelect="userSelect" />
    </div>
  </div>
</template>

<script>
import Options from './mixins/options';
import { getUserList } from '@/api/user';
import { mapState } from 'vuex';
import DiversAuditorDialog from '@/components/Common/auditProcess/module/diversAuditorDialog';
import { userChange } from '@/views/legal/process/components/formMake/utils/userField.js';

export default {
  components: { Options, DiversAuditorDialog },
  model: {
    prop: 'value',
    event: 'changeValue'
  },
  props: {
    value: {
      type: Object | Array | String | Number,
      default: null
    },
    element: {
      type: Object,
      default: () => ({})
    },
    isPreView: { // 是否配置中
      type: Boolean,
      default: false
    },
    isInDetail: { // 是否详情页展示，isDetail可能因为事件而改变，导致实际在详情页而 isDetail 为false，这个属性不会改变，详情页永远为true
      type: Boolean,
      default: false
    },
    formOptions: {
      type: Object,
      default: () => ({})
    },
    /** 为子表单字段才有 */
    subformIndex: { // 当前所在行
      type: Number,
      default: 0
    },
    subformElement: { // 当前所在子表单
      type: Object,
      default: () => ({})
    },
    eventData: { // 事件
      type: Object,
      default: null
    }
  },
  data() {
    return {
      userList: [],
      flag: true
    };
  },
  computed: {
    ...mapState({
      'initUserList': state => state.user.userList,
      'userInfo': state => state.user.userInfo
    }),
    computedValue: {
      get() {
        return this.isEmptyVal(this.value) ? null : this.value;
      },
      set(val) {
        this.$emit('changeValue', val);
        // 子表单内部人员清空之后value仍然有值问题,此处清空
        if (!val && this.element.isSubTable && !this.element.options.multiple) {
          this.$set(this.element, 'value', null);
        }
        this.handleFormUserSelect(this.element, val);
        userChange(this.element, this.formOptions, {
          userInfo: this.userInfo,
          subformIndex: this.subformIndex,
          handleFormUserSelect: this.handleFormUserSelect,
          eventData: this.eventData,
          isInDetail: this.isInDetail
        });
      }
    },
    defaultValue() {
      const value = this.computedValue;
      if (!value) return [];
      if (Array.isArray(value)) {
        return value;
      }
      return [value];
    },
    modelValue() {
      if (!this.defaultValue) return '--';
      return this.defaultValue.map(i => i.userName).join(',');
    }
  },
  watch: {
    'element.options.multiple': {
      handler(val) {
        this.initValue(val);
      },
      deep: true
    }
  },
  created() {
    if (this.initUserList && this.initUserList.length) {
      this.userList = this.initUserList;
    } else {
      this.getUser('', true);
    }
  },
  methods: {
    isEmptyVal(val) {
      return JSON.stringify(val) === '{}' || (!val && val !== 0) || (Array.isArray(val) && !val.length);
    },
    handleFormUserSelect(element, value) {
      const cloneElement = _.cloneDeep(element);
      if (value && !Array.isArray(value)) cloneElement['_post'] = value && value.post || null;
      cloneElement._postValue = { ...value };
      this.$emit('handleFormUserSelect', cloneElement);
    },
    userSelect(data) {
      const selectUser = data.selectUser;
      if (!selectUser || selectUser.length === 0) {
        this.$set(this.element, 'value', multiple ? [] : '');
        return;
      }
      const multiple = this.element.options.multiple;
      if (multiple) {
        this.computedValue = selectUser;
      } else {
        this.computedValue = selectUser[0];
      }
      this.$emit('clearValidate', this.element.key);
    },
    addSender() {
      if (this.element.options.disabled && !this.isInDetail) return;
      this.$refs.auditorDialog.dialogVisible = true;
      let val = this.computedValue || [];
      // val = Array.isArray(val) ? val : [val];
      // val为空对象时不应直接传递一个值为空对象的数组,应传递空数组
      val = Array.isArray(val) ? val : (Object.keys(val).length === 0 ? [] : [val]);
      const multiple = this.element.options.multiple;
      this.$refs.auditorDialog.initSenderData(val, '选择人员', multiple ? 50 : 1);
    },
    clearUser() {
      const multiple = this.element.options.multiple;
      this.$set(this.element, 'value', multiple ? [] : '');
    },
    initValue(multiple) {
      if (!this.isPreView) return;
      let val = this.computedValue;
      let value = multiple ? [] : '';
      if (val && ((Array.isArray(val) && val.length) || val.id)) {
        val = Array.isArray(val) ? val[0] : val;
        if (Array.isArray(value)) {
          value.push(val);
        } else {
          value = val;
        }
      }
      this.$set(this.element, 'value', value);
      this.flag = false;
      this.$nextTick(() => {
        this.flag = true;
      });
    },
    filterData(name) {
      this.getUser(name);
    },
    getUser(userName = '', isInit = false) {
      const params = {
        page: 1, perPage: 20
      };
      if (userName) params.userName = userName;
      getUserList(params).then(res => {
        if (res.code === 200) {
          this.userList = res.data.items;
          if (isInit) {
            this.$store.commit('SET_USERLIST', res.data.items);
          }
        }
      });
    },
    handleClear() {
      this.getUser();
    },
    handleChange(val) {
      this.$emit('userChange', { key: this.element.key, val });
    }
  }
};
</script>

<style lang="scss" scoped>
.hide {
  display: none;
}
.input {
  padding: 0 8px;
  font-size: 14px;
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid #DCDFE6;
  line-height: 32px;
  height: 32px;
  cursor: pointer;
  position: relative;
  display: flex;
  align-items: center;
  &.disabled {
    background-color: #F5F7FA;
    border-color: #E4E7ED;
    color: #C0C4CC;
    cursor: not-allowed;
  }
  .value {
    color: #333;
  }
  .placeholder {
    color: #C0C4CC;
  }
  .icon {
    font-size: 14px;
    color: #C0C4CC;
    position: absolute;
    right: 2px;
    top: 50%;
    display: none;
    transform: translateY(-50%);
  }
  &:hover  {
    .icon {display: block;}
  }
}
.width240 {
  width: 100%;
}
</style>
